#include "Clock.h";

extern LiquidCrystal lcd;

bool new_day;
bool new_hr;
bool new_min;
bool new_sec;

void Clock::init(){
  new_hr = false;
  new_min = false;
  new_sec = false;
  RTC.read(curr_time);

  last_day   = curr_time.Wday;
  last_hr    = curr_time.Hour;
  last_min   = curr_time.Minute;
  last_sec   = curr_time.Second;

}

void Clock::update_clock(){
  new_day = false;
  new_hr = false;
  new_min = false;
  new_sec = false;
  
  RTC.read(curr_time);
  

  if ( last_day !=  curr_time.Wday ){
    new_day = true;
  }

  if ( last_hr !=  curr_time.Hour){
    new_hr = true;
  }

  if ( last_min !=  curr_time.Minute ){
    new_min = true;
  }

  if ( last_sec !=  curr_time.Second ){
    new_sec = true;
  }

  last_day   = curr_time.Wday;
  last_hr    = curr_time.Hour;
  last_min   = curr_time.Minute;
  last_sec   = curr_time.Second;

}

void Clock::print_time_min(int hr,int min){
  if ( hr < 10 ){
    lcd.print(" ");
  }
  lcd.print(hr);
  lcd.print(":");
  if ( min < 10 ){
    lcd.print("0");
  }
  lcd.print(min);
}
void Clock::print_time(int hr,int min,int sec){
  print_time_min(hr,min);
  lcd.print(":");
  if ( sec  < 10 ){
    lcd.print("0");
  }
  lcd.print(sec);//read seconds

}

void Clock::print_time_min(){
 
  if ( curr_time.Hour < 10 ){
    lcd.print(" ");
  }
  lcd.print(curr_time.Hour); //read the hour 
  lcd.print(":");
  if ( curr_time.Minute < 10 ){
    lcd.print("0");
  }
  lcd.print(curr_time.Minute);//read minutes 

}

void Clock::print_time_sec(){
  print_time_min();
  lcd.print(":");
  if ( curr_time.Second  < 10 ){
    lcd.print("0");
  }
  lcd.print(curr_time.Second);//read seconds
}

void Clock::print_date(int yr ,int  mth ,int date ,int day){
  lcd.print(date);
  lcd.print("/");
  lcd.print(mth);
  lcd.print("/");
  lcd.print(yr);
  lcd.print(" ");
  strcpy_P(buffer, (char*)pgm_read_word(&(  days_names_table[  (day -1 ) ]     )));
  lcd.print(buffer );
}

void Clock::print_date(){
  
  if ( curr_time.Day < 10 ){
    lcd.print("0");
  }
  lcd.print( curr_time.Day );//read date
  lcd.print("/");
  if ( curr_time.Month < 10 ){
    lcd.print("0");
  }
  lcd.print(curr_time.Month);//read month
  lcd.print("/");
  lcd.print(tmYearToCalendar(curr_time.Year)); //read year 

}

void Clock::print_day(){
 
  strcpy_P(buffer, (char*)pgm_read_word(&(  days_names_table[  ( curr_time.Wday  -1 ) ]     )));
  lcd.print(buffer );

}

void Clock::set_time(int hr,int min,int sec){
  tmElements_t tm;
  RTC.read(tm);
  
  tm.Second = sec;
  tm.Minute = min;
  tm.Hour = hr;
  
  RTC.write(tm);
  
}

void Clock::set_date(int yr,int mth,int date,int day){
  tmElements_t tm;
  RTC.read(tm);
   
  tm.Wday = day;
  tm.Day = date;
  tm.Month = mth;
  tm.Year = CalendarYrToTm(yr);
  
  
  RTC.write(tm);
  
}





